package other.xsy.passlys;

import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEvent;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventRequest;
import com.rkhd.platform.sdk.creekflow.autoflowevent.AutoFlowEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import other.xsy.passlys.util.HCXObjectService;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 合同自动创建，处理订单下的订单明细数据
 * @Author: 黎炎松
 * @Date: 2024/4/12 11:22
 */
public class CreateContractDealOrderDetail implements AutoFlowEvent {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "合同自动创建，处理订单下的订单明细数据 ==> ";

    @Override
    public AutoFlowEventResponse execute(AutoFlowEventRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId() + " , ProcessInstanceId:" + request.getProcessInstanceId());
        logger.info(request.toString());
        AutoFlowEventResponse response = new AutoFlowEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        dealOrderDetail(request.getDataId());
        return response;
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        CreateContractDealOrderDetail contractDealOrderDetail = new CreateContractDealOrderDetail();
        //contractDealOrderDetail.dealOrderDetail(3233306948767050L);
        //contractDealOrderDetail.batchDealContract();
    }

    /**
     * 批量处理历史合同数据
     */
    public void batchDealContract() throws ApiEntityServiceException {
        String sql = "select id,title from contract where SF_ID__c is null";
        List<Contract> contactList = hcxObjectService.query(sql, Contract.class);
        CreateContractDealOrderDetail contractDealOrderDetail = new CreateContractDealOrderDetail();
        for (Contract contract : contactList) {
            contractDealOrderDetail.dealOrderDetail(contract.getId());
        }
    }

    /**
     * 根据合同、处理订单详情
     * @param contractId
     */
    private void dealOrderDetail(Long contractId) {
        try {
            logger.debug(LOGGER_MSG + " 处理开始: " + contractId);

            // 查找订单根据合同id （场景下一个合同只有一个订单）
            String sql = "select id,po,contractId from _order where contractId = " + contractId + " and customItem210__c = 1";
            Order order = hcxObjectService.queryOne(sql, Order.class);
            if (order == null) {
                logger.debug(LOGGER_MSG + " 当前合同下没有订单");
                return;
            }

            // 查找订单下的订单明细
            sql = "select id,name,productId,describe__c,time1__c,number__c from orderProduct " +
                    "where orderId = " + order.getId() + " order by name";
            List<OrderProduct> orderProductList = hcxObjectService.query(sql, OrderProduct.class);
            if (orderProductList == null || orderProductList.size() <= 0) {
                logger.debug(LOGGER_MSG + " 当前订单没有订单明细 ");
                return;
            }

            /*
                对订单明细进行处理
                describe__c 对应合同描述
                time1__c 坐席包含时间
                number__c 合同打印编号
             */
            int numberValue = 3; // 如果坐席包含时间有大于0的值则从5开始
            LinkedHashMap numberSortMap = new LinkedHashMap<String, Integer>(){
                {
                    put("电话座席账号基础月租服务费", -1);
                    put("手机号码月租服务费", -1);
                    put("外呼服务费费率", -1);
                    put("呼入服务费费率", -1);
                }
            };
            // 获取 index
            for (int i = 0; i < orderProductList.size(); i++) {
                // 获取产品信息
                OrderProduct orderProduct = orderProductList.get(i);
                Long productId = orderProduct.getProductId();
                Product product = new Product();
                product.setId(productId);
                product = hcxObjectService.get(product);

                // 赋值合同描述字段
                String contractDes = product.getContractDescription__c();

                // 赋值坐席包含时间字段 -1 0 1
                int timeValue = -1;
                if (StringUtils.isNotEmpty(contractDes)) {
                    orderProduct.setDescribe__c(contractDes);
                    logger.debug(LOGGER_MSG + " 合同描述: " + contractDes);

                    timeValue = 0;
                    // 判断是否取合同描述中的数值
                    if (contractDes.indexOf("电话座席账号基础月租服务费") != -1) {
                        Pattern pattern = Pattern.compile("\\d+");
                        Matcher matcher = pattern.matcher(contractDes);
                        if (matcher.find()) {
                            numberValue = 5;
                            timeValue = Integer.valueOf(matcher.group());
                            // 设置合同编码为 1
                            orderProduct.setNumber__c("1");
                            logger.debug(LOGGER_MSG + " 合同描述找到数字: " + matcher.group());
                        } else {
                            logger.debug(LOGGER_MSG + " 合同描述中没有找到数字");
                        }
                    }

                    // 对文案进行判断 给map赋值集合下标
                    if (numberSortMap.containsKey(contractDes)) {
                        numberSortMap.put(contractDes, i);
                    }
                }
                orderProduct.setTime1__c(Long.valueOf(timeValue));
            }


            /*
                再次循环对坐席包含时间为0的进行编号字段处理 大于0的编号为: 1; 坐席包含时间为 -1 不需要赋值;
                按照文案进行排序
                    电话座席账号基础月租服务费
                    手机号码月租服务费
                    外呼服务费费率
                    呼入服务费费率
             */
            for (Object value : numberSortMap.values()) {
                Integer index = (Integer) value;
                if (index > -1) {
                    // 赋值且对编号进行 + 1
                    orderProductList.get(index).setNumber__c(String.valueOf(numberValue++));
                }
            }

            logger.debug(LOGGER_MSG + " 更新数据: " + orderProductList);

            // 批量进行保存
            Boolean update = hcxObjectService.batchUpdate(orderProductList);
            if (!update) {
                logger.debug(LOGGER_MSG + " 批量保存异常");
            }

        } catch (ApiEntityServiceException e) {
            logger.debug(LOGGER_MSG + " 处理异常");
        }
    }

}
